package com.amithkoujalgi.framework.rest.util;


import java.io.StringWriter;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;


public class Templater
{
	private String src;
	VelocityEngine ve = new VelocityEngine();

	public Templater (String src)
	{
		this.src = src;
	}

	private void haltIfNotLoaded() throws Exception
	{
		if( src == null )
		{
			throw new Exception( "Template resource not loaded" );
		}
	}

	public String build( Map<String, String> keyValues ) throws Exception
	{
		haltIfNotLoaded();
		ve.setProperty( RuntimeConstants.RESOURCE_LOADER, "classpath" );
		ve.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName() );
		ve.init();
		Template t = ve.getTemplate( src );
		VelocityContext context = new VelocityContext();
		for( Entry<String, String> e : keyValues.entrySet() )
		{
			context.put( e.getKey(), e.getValue() );
		}
		StringWriter writer = new StringWriter();
		t.merge( context, writer );
		return writer.toString();
	}
}
